package com.group15.phms;

import java.util.ArrayList;

//import com.group15.droidmd.R;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.TextView.OnEditorActionListener;
import android.support.v4.app.NavUtils;

public class Diet extends Activity 
{
	DatabaseHelper db;
	SharedPreferences logins;
	String currentUser;
	
	//An array of meals and weights is created.
	public ArrayList<Meal> meals = new ArrayList<Meal>();
	public ArrayList<Weight> weights = new ArrayList<Weight>();
	
	//Tracks if an action button, or regular button is clicked.
	//buttonTracker: 0 = neutral, 1 = meals, 2 = weights.
	public int buttonTracker = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_diet);
		
		logins = getSharedPreferences("logins",MODE_PRIVATE);
		currentUser = logins.getString("currentUser","INVALID");
		db= new DatabaseHelper(getApplicationContext());
		
		//Hardcoded meals. In order: Title, Type, Note, Date. All are text files, no conversion necessary.
		meals.add(new Meal("Oatmeal", "400", "04/15/2014", "Add more milk next time."));
		meals.add(new Meal("Sandwich", "300", "04/15/2014", "It turns out I dont like turkey."));
		meals.add(new Meal("Pasta", "800" , "04/15/2014", "Delicious."));
		
		//Hardcoded weights. In order: Title, Type, Note, Date. All are text files, no conversion necessary.
		weights.add(new Weight("250", "Not Healthy", "01/01/2013", "My starting weight."));
		weights.add(new Weight("200", "Near Healthy", "06/15/2013", "Half way there."));
		weights.add(new Weight("150", "Healthy", "01/01/2014", "Weight goal reached."));
		
		//Simulates meals button being clicked, this is the default page the user sees.
		ButtonMealsClicked(findViewById(R.id.buttonMeals1));
		setupActionBar();
	}

	/**
	 * Set up the {@link android.app.ActionBar}.
	 */
	private void setupActionBar() 
	{

		getActionBar().setDisplayHomeAsUpEnabled(true);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) 
	{
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.diet, menu);
		return true;
	}
	
	Intent intent;
	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		switch (item.getItemId()) 
		{
			case android.R.id.home:
				// This ID represents the Home or Up button. In the case of this
				// activity, the Up button is shown. Use NavUtils to allow users
				// to navigate up one level in the application structure. For
				// more details, see the Navigation pattern on Android Design:
				//
				// http://developer.android.com/design/patterns/navigation.html#up-vs-back
				//
				NavUtils.navigateUpFromSameTask(this);
				return true;
			case R.id.action_add:
	            Add();
	            return true;
			case R.id.action_logout:
				intent = new Intent(this, Login.class);
		    	startActivity(intent);
		    	finish();
				return true;
			case R.id.action_search:
				intent = new Intent(this, Search.class);
		    	startActivity(intent);
				return true;
		}
		return super.onOptionsItemSelected(item);
	}

	public void Add()
	{
		if (buttonTracker == 1)
		{
			//A dialog to add meals is created.
			final Dialog dialog = new Dialog(this);
			dialog.setContentView(R.layout.dialog_add_meal);
			dialog.setTitle("Add Meal");
			
			//The dialog is filled with Edit Text boxes to grab user input.
			//	In order: Title, Calories, Date, Note.
			final EditText title = (EditText) dialog.findViewById(R.id.editTextMealAdd);
			final EditText cal = (EditText) dialog.findViewById(R.id.editTextCalAdd);
			final EditText date = (EditText) dialog.findViewById(R.id.editTextDateAdd);
			final EditText note = (EditText) dialog.findViewById(R.id.editTextNoteAdd);
					
			//The add button and cancel button are created.
			final Button buttonCancel = (Button) dialog.findViewById(R.id.buttonCancel);
			final Button buttonAdd = (Button) dialog.findViewById(R.id.buttonAdd);
			
			note.setOnEditorActionListener(new OnEditorActionListener() 
			{
			    @Override
			    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) 
			    {
			        if(actionId == EditorInfo.IME_ACTION_DONE)
			        {
			        	buttonAdd.performClick();
			        }
			    return false;
			    }
			});
			
			//The dialog is shown.
			dialog.show();

			buttonCancel.setOnClickListener(new OnClickListener() 
			{
				@Override
				public void onClick(View v) 
				{
					dialog.dismiss();
				}
			});
			
			//If the Add button is pressed the a new meal is added. A click on the meal button
			//	is simulated, refreshing the list of meals. The Add dialog closes.
			buttonAdd.setOnClickListener(new OnClickListener() 
			{
				@Override
				public void onClick(View v) 
				{
					String titleString = title.getText().toString();
					String typeString = cal.getText().toString();
					String dateString = date.getText().toString();
					String noteString = note.getText().toString();
					
					meals.add(new Meal(titleString, typeString, dateString, noteString));
					Toast.makeText(Diet.this, "Meal added.", Toast.LENGTH_SHORT).show();
					ButtonMealsClicked(findViewById(R.id.buttonMeals1));
					dialog.dismiss();
				}
			});
		}
		else if(buttonTracker == 2)
		{
			//A dialog to add weights is created.
			final Dialog dialog = new Dialog(this);
			dialog.setContentView(R.layout.dialog_add_weight);
			dialog.setTitle("Add Weight");
			
			//The dialog is filled with Edit Text boxes to grab user input.
			//	In order: Weight, Health, Date, Note.
			final EditText weight = (EditText) dialog.findViewById(R.id.editTextWeightAdd);
			final EditText health = (EditText) dialog.findViewById(R.id.editTextHealthAdd);
			final EditText date = (EditText) dialog.findViewById(R.id.editTextDateAdd);
			final EditText note = (EditText) dialog.findViewById(R.id.editTextNoteAdd);
					
			//The add button and cancel button are created.
			final Button buttonCancel = (Button) dialog.findViewById(R.id.buttonCancel);
			final Button buttonAdd = (Button) dialog.findViewById(R.id.buttonAdd);
			
			note.setOnEditorActionListener(new OnEditorActionListener() 
			{
			    @Override
			    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) 
			    {
			        if(actionId == EditorInfo.IME_ACTION_DONE)
			        {
			        	buttonAdd.performClick();
			        }
			    return false;
			    }
			});
			
			//The dialog is shown.
			dialog.show();

			//If the Cancel button is pressed the dialog closes.
			buttonCancel.setOnClickListener(new OnClickListener() 
			{
				@Override
				public void onClick(View v) 
				{
					dialog.dismiss();
				}
			});
			
			//If the Add button is pressed the a new weight is added. A click on the weight button
			//	is simulated, refreshing the list of weights. The Add dialog closes.
			buttonAdd.setOnClickListener(new OnClickListener() 
			{
				@Override
				public void onClick(View v) 
				{
					String titleString = weight.getText().toString();
					String typeString = health.getText().toString();
					String dateString = date.getText().toString();
					String noteString = note.getText().toString();
					
					weights.add(new Weight(titleString, typeString, dateString, noteString));
					Toast.makeText(Diet.this, "Weight added.", Toast.LENGTH_SHORT).show();
					ButtonWeightsClicked(findViewById(R.id.buttonWeights1));
					dialog.dismiss();
				}
			});
		}
	}
	
	public void ButtonMealsClicked(View v)
	{
		buttonTracker = 1;
		MealElementClicked();
	}
	
	public void ButtonWeightsClicked(View v)
	{
		buttonTracker = 2;
		WeightElementClicked();
	}
	
	private void MealElementClicked()
	{	
		//A custom adapter for the weights is also initiated. The code for the custom adapter is at the end.
		//The lists for weights is also initiated.
		ArrayAdapter<Meal> adapterM = new MealAdapter();
		ListView listM = (ListView) findViewById(R.id.listViewDiet1);
		
		//The custom adapter for the weights list is set.
		listM.setAdapter(adapterM);
		
		//An alert dialog is created.
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		
		//If a meal is clicked in the list, the following code runs.
		listM.setOnItemClickListener(new AdapterView.OnItemClickListener() 
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id)
			{	
				//The clicked meal is grabbed.
				//A string is created from the meals information.
				//The alert dialogs title and message is set.
				final int p = position;
				Meal clicked = meals.get(position);
				String message = clicked.getMealDate() + "\n" + clicked.getMealCal() + "\n\"" + clicked.getMealNote() + "\"";
				alert.setTitle(clicked.getMeal());
				alert.setMessage(message);
				
				//When the user clicks the OK button the dialog closes.
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() 
				{
					public void onClick(DialogInterface dialog, int whichButton) 
					{
						//Exit screen.
					}
				});
				
				alert.setNegativeButton("Remove", new DialogInterface.OnClickListener() 
				{
					public void onClick(DialogInterface dialog, int whichButton) 
					{
						//The selected meal is removed.
						//A toast confirms the meal is removed.
						//A click on the meal button is simulated, refreshing the list of meals.
						meals.remove(p);
						Toast.makeText(Diet.this, "Meal removed.", Toast.LENGTH_SHORT).show();
						ButtonMealsClicked(findViewById(R.id.buttonMeals1));
					}
				});

				//The alert is shown.
				alert.show();
			}
		});
	}
	
	private void WeightElementClicked()
	{	
		//A custom adapter for the weights is also initiated. The code for the custom adapter is at the end.
		//The lists for weights is also initiated.
		ArrayAdapter<Weight> adapterW = new WeightAdapter();
		ListView listW = (ListView) findViewById(R.id.listViewDiet1);
		
		//The custom adapter for the weights list is set.
		listW.setAdapter(adapterW);
		
		//An alert dialog is created.
		final AlertDialog.Builder alert = new AlertDialog.Builder(this);
		
		//If a weight is clicked in the list, the following code runs.
		listW.setOnItemClickListener(new AdapterView.OnItemClickListener() 
		{
			@Override
			public void onItemClick(AdapterView<?> parent, View viewClicked, int position, long id)
			{
				//The clicked meal is grabbed.
				//A string is created from the meals information.
				//The alert dialogs title and message is set.
				final int p = position;
				Weight clicked = weights.get(position);
				String message = clicked.getWeightDate() + "\n"  + clicked.getWeightHealth() + "\n\"" + clicked.getWeightNote() + "\"";
				alert.setTitle(clicked.getWeight());
				alert.setMessage(message);
				
				//When the user clicks the OK button the dialog closes.
				alert.setPositiveButton("OK", new DialogInterface.OnClickListener() 
				{
					public void onClick(DialogInterface dialog, int whichButton) 
					{
						//Exit screen.
					}
				});
				
				alert.setNegativeButton("Remove", new DialogInterface.OnClickListener() 
				{
					public void onClick(DialogInterface dialog, int whichButton) 
					{
						//The selected weight is removed.
						//A toast confirms the weight is removed.
						//A click on the weight button is simulated, refreshing the list of weights.
						weights.remove(p);
						Toast.makeText(Diet.this, "Weight removed.", Toast.LENGTH_SHORT).show();
						ButtonWeightsClicked(findViewById(R.id.buttonWeights1));
					}
				});

				//The alert is shown.
				alert.show();
			}
		});
	}
	
	private class MealAdapter extends ArrayAdapter<Meal>
	{
		public MealAdapter()
		{
			super(Diet.this, R.layout.dialog_diet, meals);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			View itemView = convertView;
			if (itemView == null)
			{
				itemView = getLayoutInflater().inflate(R.layout.dialog_diet, parent, false);
			}
			
			//Will use the current meal selected.
			Meal currentMeal = meals.get(position);
			
			//Sets the text for meal.
			TextView textViewTitle = (TextView) itemView.findViewById(R.id.textViewTitle);
			textViewTitle.setText(currentMeal.getMeal());
			
			//Sets the text for date.
			TextView textViewDate = (TextView) itemView.findViewById(R.id.textViewDate);
			textViewDate.setText(currentMeal.getMealDate());
			
			//Sets the text for calories.
			TextView textViewType = (TextView) itemView.findViewById(R.id.textViewType);
			textViewType.setText(currentMeal.getMealCal());
			
			return itemView;
		}
	}
	
	private class WeightAdapter extends ArrayAdapter<Weight>
	{
		public WeightAdapter()
		{
			super(Diet.this, R.layout.dialog_diet, weights);
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) 
		{
			View itemView = convertView;
			if (itemView == null)
			{
				itemView = getLayoutInflater().inflate(R.layout.dialog_diet, parent, false);
			}
			
			//Will use the current weight selected.
			Weight currentWeight = weights.get(position);
			
			//Sets the text for weight.
			TextView textViewTitle = (TextView) itemView.findViewById(R.id.textViewTitle);
			textViewTitle.setText(currentWeight.getWeight());
			
			//Sets the text for health.
			TextView textViewType = (TextView) itemView.findViewById(R.id.textViewType);
			textViewType.setText(currentWeight.getWeightHealth());
			
			//Sets the text for date.
			TextView textViewDate = (TextView) itemView.findViewById(R.id.textViewDate);
			textViewDate.setText(currentWeight.getWeightDate());
			
			return itemView;
		}
	}
}
